package com.sofwin.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sofwin.dto.UserDto;
import com.sofwin.mapper.SUserMapper;
import com.sofwin.pojo.SUser;
import com.sofwin.pojo.SUserExample;
import com.sofwin.pojo.SUserExample.Criteria;
import com.sofwin.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private SUserMapper mapper;
	@Override
	public PageInfo<UserDto> selectUserByPage(SUser user, Integer pageNumber, Integer pageSize) {
		PageHelper.startPage(pageNumber, pageSize);
		List<UserDto> users = mapper.selectUsersByPage(user);
		return new PageInfo<UserDto>(users);
	}

	@Override
	public SUser selectUserById(Integer id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public Boolean saveOrUpdate(SUser user) {
		Boolean status = false;
		int flag = 0;
		if(user.getId()!=null) {
			flag = mapper.updateByPrimaryKeySelective(user);
		}else {
			user.setCreateTime(new Date());
			flag = mapper.insertSelective(user);
		}
		status = flag==1?true:false;
		return status;
	}

	@Override
	public Boolean deleteById(Integer id) {
		return mapper.deleteByPrimaryKey(id)==1?true:false;
	}

	@Override
	public Boolean deleteByIds(String[] ids) {
		Boolean status = false;
		int flag =0;
		for(String id:ids) {
			if(deleteById(Integer.parseInt(id))) {
				flag++;
			}
		}
		status = flag==ids.length?true:false;
		return status;
	}

	@Override
	public boolean checkLogin(SUser user) {
		boolean status = false;
		SUserExample example = new SUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserNameEqualTo(user.getUserName());
		criteria.andPwdEqualTo(user.getPwd());
		List<SUser> users = mapper.selectByExample(example );
		if(users!=null && users.size()==1) {
			status = true;
		}
		return status;
	}

	@Override
	public SUser selectUserByUserNameAndPwd(SUser user) {
		SUserExample example = new SUserExample();
		Criteria criteria = example.createCriteria();
		if(user.getUserName()!=null && !"".equals(user.getUserName())) {
		criteria.andUserNameEqualTo(user.getUserName());
		}
		if(user.getPwd()!=null && !"".equals(user.getPwd())) {
		criteria.andPwdEqualTo(user.getPwd());
		}
		List<SUser> users = mapper.selectByExample(example);
		if(users!=null && users.size()==1) {
		return users.get(0);
		}
		return null;
	}

}
